package com.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.bean.Permission;
import com.bean.RolePermission;
import com.bean.User;

/**
 * @author author : 张鹏
 * @date createTime：2018年3月22日 下午9:17:06
 * @Description: 权限拦截器
 */
public class PermissionInterceptor implements HandlerInterceptor {
	String[] notFilter = { "user/login", "login" };

	String[] jspNotFilter = {"login","noPermission","welcome", "productionPlanManageMenu", "foodManageMenu",
			"stockManageMenu" ,"recordMenu","dataAnalyzeMenu","systemManageMenu"};
	String url = null;

	HttpServletRequest httpRequest = null;

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		httpRequest = request;
		String requestUri = request.getRequestURI(); // 请求完整路径，可用于登陆后跳转
		String contextPath = request.getContextPath(); // 项目下完整路径
		url = requestUri.substring(contextPath.length() + 1); // 请求页面
		System.out.print("发生拦截...");
		User user = (User) request.getSession().getAttribute("userInfo");

		String returnTo1 = request.getParameter("returnTo");
		System.out.println(url + "--" + returnTo1);
		
		
		if (isNotFilter()) {
			System.out.println("不用过滤");
			return true;
		}else {
			if (user == null) { 
				System.out.println("未登录");
					if (request.getHeader("x-requested-with") != null
							&& request.getHeader("x-requested-with")
									.equalsIgnoreCase("XMLHttpRequest")) {
						System.out.println("是ajax");
						response.setHeader("sessionstatus", "timeout");
						response.addHeader("interceptorResult", "noLogin");

					} else {
						System.out.println("不是ajax");
						request.getRequestDispatcher("/WEB-INF/jsp/login.jsp")
								.forward(request, response);
					}

					return false;

			} else {
				System.out.println("已经登录");
				if (isNeedPermission()) {
					System.out.println("需要权限");
					if (isHavePermission()) {
						System.out.println("具有权限");
						return true;
					}else {
						System.out.println("不具有权限");
						if (request.getHeader("x-requested-with") != null
								&& request.getHeader("x-requested-with").equalsIgnoreCase(
										"XMLHttpRequest")) {
							System.out.print("发生ajax请求:" + url);
							response.setHeader("sessionstatus", "timeout");
							response.addHeader("interceptorResult", "noPermission");
							// response.setHeader("sessionstatus",
							// "timeout");//在响应头设置session状态
						} else {
							System.out.println("不是ajax");
							request.getRequestDispatcher("/WEB-INF/jsp/noPermission.jsp")
							.forward(request, response);
						}
						return false;
					}
				}else {
					System.out.println("不需要权限");
					return true;
				}
				
			}
		} 
	


	}

	private boolean isNotFilter() {
		boolean result = false;
		for (String s : notFilter) {
			if (url.indexOf(s) != -1) {
				// 如果uri中包含不过滤的uri，则不进行过滤
				System.out.println("不用过滤");
				return  true;
			}
		}
		if (url.equals("jsp/toJspByReturnTo")) {
			for (String s : jspNotFilter) {
				if (s.equals(httpRequest.getParameter("returnTo"))) {
					// 如果uri中包含不过滤的uri，则不进行过滤
					System.out.println("该jsp不用过滤");
					return  true;
				}
			}
			return false;
		}
		return result;
	}

	/**
	 * 是否需要权限 true为需要
	 * 
	 * @return
	 */
	private boolean isNeedPermission() {
		List<Permission> permissionList = (List<com.bean.Permission>) httpRequest
				.getSession().getAttribute("permissionInfo");
		for (Permission p : permissionList) {
			if (url.equals(p.getUrl())) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 是否具有权限
	 * 
	 * @return
	 */
	private boolean isHavePermission() {
		List<RolePermission> permissionList = (List<RolePermission>) httpRequest
				.getSession().getAttribute("userPermissionInfo");
		for (RolePermission p : permissionList) {
			if (url.equals(p.getPermission().getUrl())) {
				return true;
			}
		}
		return false;

	}
}
